import { Injectable, Logger } from '@nestjs/common';
import axios from 'axios';
import * as cheerio from 'cheerio';
import * as xlsx from 'node-xlsx';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class mtService {
  private readonly logger = new Logger(mtService.name);
  constructor() {
    this.main();
  }

  /**
   *
   * 主流程
   * @memberof mtService
   */
  async main() {
    let mt;
    mt = await this.mtHtml();
    let config = {
      // 如果将分隔符定义为空格，有可能错误的截取爬取到的数据
      // 且分隔符要避免使用正则表达式中需要转义的字符
      separator: ';;;;',
      rawDataFileName: 'data.txt',
      saveFileName: 'out.xlsx',
    };
    // 拼接爬取到的数据

    mt =
      Object.keys(mt)
        .map(key => mt[key])
        .join(config.separator) + '\n';
    let fileRoute = path.resolve(__dirname, config.rawDataFileName);
    // 使用node将数据储存到本地，使用appendFile逐条追加
    await fs.writeFile(fileRoute, mt, err => {
      if (err) throw err;
    });
    fs.readFile(fileRoute, 'utf-8', (err, data) => {
      if (err) throw err;
      this.saveFile(data);
    });
    return;
  }
  async mtHtml() {
    const url = 'http://quotes.money.163.com/f10/zycwzb_600519.html';
    try {
      let res = await axios.get(url);
      const $ = cheerio.load(res.data);
      const money = [];
      $('.scr_table')
        .find('tr')
        .eq(10)
        .find('td')
        .each(function(i, elem) {
          money[i] = $(this).text() + '^';
        });

      const year = [];
      $('.scr_table')
        .find('tr')
        .eq(0)
        .find('th')
        .each(function(i, elem) {
          year[i] = $(this).text();
        });
      return { year, money };
    } catch {
      this.logger.log('请求失败');
      return false;
    }
  }

  // 转存文本
  saveFile(data) {
    let config = {
      // 如果将分隔符定义为空格，有可能错误的截取爬取到的数据
      // 且分隔符要避免使用正则表达式中需要转义的字符
      separator: ';;;;',
      rawDataFileName: 'data.txt',
      saveFileName: 'out.xlsx',
    };
    let exportData = {
      name: '茅台数据',
      data: [
        [], // 第一行数据，分别对应A1 B1 C1的table cell的内容，即单元格标题
      ],
    };
    let fileRoute = path.resolve(__dirname, config.rawDataFileName);
    let fileName = path.resolve(__dirname, config.saveFileName);
    // 剔除无效数据
    data = data.split(/\n/).filter(r => !!r);
    // 将文本转换为符合要求的数组对象
    // this.logger.log(data, 'data');

    let seperatorPtn = data.toString().split(';;;;');
    let newMoney = [];

    seperatorPtn[1]
      .replace(/\^,/g, '^')
      .split('^')
      .map(r => {
        newMoney.push(r);
      });
    newMoney.pop();
    newMoney.unshift('茅台净利润（万元）');

    seperatorPtn.pop();
    let lab1 = seperatorPtn[0].split(',').map(r => r);
    lab1.unshift('日期');
    exportData.data['0'] = lab1;

    exportData.data['1'] = newMoney;
    this.logger.log(exportData, 'newMoney');

    // 转存数据
    // this.logger.log(exportData);
    var buffer = xlsx.build([exportData]); // Returns a buffer
    fs.writeFile(fileName, buffer, err => {
      if (err) throw err;
      console.log('保存成功');
    });
  }
  // start
  // 读取文本内容并开始转存
}
